package frwa;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class Controller extends HttpServlet {

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
            throws IOException, ServletException {
        IAction action;
        ActionResult actionResult;
        try {
            action = ActionMap.getInstance().getAction(request.getParameter("menu"));
            try {
                actionResult = action.perform(request);
                RequestDispatcher requestDispatcher = request.getRequestDispatcher(actionResult.getUrlAddress());
                request.setAttribute("TransferObject", actionResult.getFormObject());
                requestDispatcher.forward(request, response);
            } catch (NullPointerException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Действие вернуло неожиданный результат");
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
        throws IOException, ServletException {
        IAction action;
        ActionResult actionResult = null;
        try {
            action = ActionMap.getInstance().getAction(request.getParameter("parameter"));
            try {
                actionResult = action.perform(request);
                RequestDispatcher requestDispatcher = request.getRequestDispatcher(actionResult.getUrlAddress());
                request.setAttribute("TransferObject", actionResult.getFormObject());
                requestDispatcher.forward(request, response);
            } catch (NullPointerException e) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Хрень какая-то случилась в контроллере");
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
}
